package com.chen.apipassenger.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.chen.internalcommon.constant.IdentityConstants;
import com.chen.internalcommon.dto.ResponseResult;
import com.chen.internalcommon.dto.TokenResult;
import com.chen.internalcommon.util.JwtUtils;
import com.chen.internalcommon.util.RedisPrefixUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * @author chenLiuPing
 **/
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        boolean result = true;
        TokenResult tokenResult = JwtUtils.parseToken(token);
        if (tokenResult == null || !Objects.equals(tokenResult.getIdentity(), IdentityConstants.PASSENGER_IDENTITY)) {
            result = false;
            PrintWriter writer = response.getWriter();
            writer.print(JSONObject.toJSONString(ResponseResult.fail("token vaild")));
        } else {
            // 从redis中获取token来判断前端传过来的token是否合法
            String tokenKey = RedisPrefixUtils.generateAccessTokenKey(tokenResult.getPhone(), tokenResult.getIdentity());
            String tokenRedis = stringRedisTemplate.opsForValue().get(tokenKey);
            if (!StringUtils.hasText(tokenRedis)) {
                result = false;
                PrintWriter writer = response.getWriter();
                // TODO 这里返回的提示信息应该是token过期而不是不合法
                writer.print(JSONObject.toJSONString(ResponseResult.fail("token vaild")));
            }
        }
        return result;
    }
}
